import { createSlice } from "@reduxjs/toolkit";
// import { AppState } from "@store/index";

// 状态切片管理的状态的类型
interface ChannelNews {
    // 频道id -> 新闻列表
    [cid: string]: ChannelNewsItem;
}


interface ChannelNewsItem {
    results: News[];
    pre_timestamp: string | null;
    distance: number;
}

const initialState: ChannelNews = {};

// 创建用于管理新闻列表数据的状态切片
const { reducer: newsReducer, actions } = createSlice({
    name: "news",
    initialState,
    reducers: {
        // 保存新闻列表
        saveNews(state, action) {
            const { cid, results, pre_timestamp } = action.payload;
            if (typeof state[cid] === 'undefined') {
                state[cid] = {
                    results,
                    pre_timestamp,
                    distance: 0
                }
            } else {
                state[cid].results.push(...results);
                state[cid].pre_timestamp = pre_timestamp
            }
        },
        // 保存滚动距离
        saveDistance(state, action) {
            state[action.payload.cid].distance = action.payload.distance;
        },
    },
});

// 新闻列表状态选择器
export const selectChannelNews =
    (cid: string) =>
        (state: any): undefined | ChannelNewsItem => {
            return state.newsReducer[cid];
        };

export const { saveNews, saveDistance } = actions;
export default newsReducer;